import re

from rest_framework import serializers
from users.models import User

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model=User
        fields=('id','username','mobile','email','password')
        extra_kwargs = {
            'password':{
                'write_only':True,
                'max_length':20,
                'min_length':8
            },
            'username':{
                'max_length': 20,
                'min_length': 5
            }
        }

    # 手机格式验证
    def validate_mobile(self,attrs):
        if not re.match(r'1[3-9]\d{9}',attrs):
            raise serializers.ValidationError('手机格式不正确')

        # 唯一值判断
        try:
            user = User.objects.get(mobile=attrs)
        except:
            user = None
        if user:
            raise serializers.ValidationError('手机号已注册')

        return attrs

    # 重写create方法，用户增加时调用
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
